package com.zyz.forum.controller;

import com.zyz.forum.common.AppResult;
import com.zyz.forum.common.ResultCode;
import com.zyz.forum.config.AppConfig;
import com.zyz.forum.model.Message;
import com.zyz.forum.model.User;
import com.zyz.forum.service.IMessageService;
import com.zyz.forum.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Api(tags = "站内信接口")
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IUserService userService;
    @Resource
    private IMessageService messageService;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接收方") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("发送内容") @RequestParam("content") @NonNull String content) {
        // 获取登陆状态，如果是禁言则不能发布
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        if (user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 不能给自己发
        if (user.getId().equals(receiveUserId)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 校验接收者是否存在
        User existRecieveUser = userService.selectById(receiveUserId);
        if (existRecieveUser == null || existRecieveUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 封装对象
        Message updateMessage = new Message();
        updateMessage.setPostUserId(user.getId());
        updateMessage.setReceiveUserId(receiveUserId);
        updateMessage.setContent(content);
        // 调用service
        messageService.create(updateMessage);
        // 返回结果
        log.info("发送成功！");
        return AppResult.success("发送成功！");
    }

    @ApiOperation("获取未读数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        // 调用service
        Integer count = messageService.selectUnreadCount(user.getId());
        return AppResult.success(count);
    }

    @ApiOperation("查询用户的站内信列表")
    @PostMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        // 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        // 调用service
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        // 直接返回结果
        return AppResult.success(messages);
    }

    @ApiOperation("修改站内信状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信id") @RequestParam("id") @NonNull Long id) {
        // 查询站内信信息
        Message message = messageService.selectById(id);
        // 判断站内信是否存在
        if (message == null || message.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        // 判断站内信是否是自己的
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        if (!user.getId().equals(message.getReceiveUserId())) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用service
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    @ApiOperation("站内信回复")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("要回复的内容") @RequestParam("content") @NonNull String content){
        // 获取session中信息,作为发送方
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        // 校验用户状态
        if (user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 通过repliedId获取发送方用户id作为接收方用户id
        Message message = messageService.selectById(repliedId);
        if (message == null || message.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        // 不能给自己发
        if (user.getId().equals(message.getPostUserId())) {
            return AppResult.failed("不能回复自己的站内信");
        }
        Long repliedUserId = message.getPostUserId();
        // 构造message
        Message updateMessage = new Message();
        updateMessage.setPostUserId(user.getId());
        updateMessage.setReceiveUserId(repliedUserId);
        updateMessage.setContent(content);
        // 调用service层
        messageService.reply(repliedId,updateMessage);
        // 回复站内信成功
        log.info("站内信回复成功 repliedId: {}" , repliedId);
        return AppResult.success();
    }


}
